import 'dart:math';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:loop_page_view/loop_page_view.dart';

import 'package:page_view_dot_indicator/page_view_dot_indicator.dart';
import 'package:stop_watch_timer/stop_watch_timer.dart';
import 'package:wk_robot2/app/utils/CommonUtil.dart';
import 'package:wk_robot2/app/utils/NetWorkUtil.dart';
import 'package:wk_robot2/app/widget/CommonWidgets.dart';
import 'package:wk_robot2/generated/CmSquareAction.pb.dart';
import '../../../../generated/AlphaResponse.pb.dart';
import '../../../../generated/GetRobotConfiguration.pb.dart';
import '../../../const/AppConst.dart';
import '../../../event/DataCallBack.dart';
import '../../../event/MsgContentEvent.dart';
import '../../../event/WkEventListener.dart';
import '../../../logger/Logger.dart';
import '../../../models/ActionItem.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../robot_comm/cmd_const.dart';
import '../../../robot_comm/event_handler.dart';
import '../../../robot_comm/mqtt_comm_manager.dart';
import '../../../style/app_colors.dart';
import '../../../widget/tips.dart';

class ActionSquaresView3 extends StatefulWidget {
  ActionSquaresView3({super.key});

  @override
  State<StatefulWidget> createState() {
    return ActionSquareViewState();
  }
}

class ActionSquareViewState extends State with TickerProviderStateMixin {

  LoopPageController? _loopPageController;
  LoopPageController? _headerLoopPageController;
  int currentIndex = 0;
  int dotGroupSize = 0;


  bool robotWhetherOnline = false;
  Map<String,List<ActionItem>> actionMp = Map<String, List<ActionItem>>();

  //实际页面.
  List<Widget> groupItems = List.generate(3, (index) => Center(
    child: Text('加载中...'),
  ));

  bool danceChecked = true;
  bool actionChecked = false;
  bool unexpectedChecked = false;

  int danceFirsPageIndex = 0;
  int actionFirsPageIndex = 0;
  int unexpectedFirsPageIndex = 0;


  bool showHeader = false;


  List<ActionItem> headerDataSource = [];

  // late AnimationController _signalController;
  late IntTween _tween;

  AnimationController? currentIconAnimationController;
  AnimationController? currentSignalAnimationController;

  ActionItem? currentActionItem;

  StopWatchTimer? currentCountDownWatchTimer;

  bool hasNetWork = false;
  var mNetSubscription =  null;

  //actionStatement
  List<ImageProvider> signalImages = [
    AssetImage('assets/images/play_sequence_0.webp'),
    AssetImage('assets/images/play_sequence_1.webp'),
    AssetImage('assets/images/play_sequence_2.webp'),

    AssetImage('assets/images/play_sequence_3.webp'),
    AssetImage('assets/images/play_sequence_4.webp'),
    AssetImage('assets/images/play_sequence_5.webp'),

    AssetImage('assets/images/play_sequence_6.webp'),
    AssetImage('assets/images/play_sequence_7.webp'),
    AssetImage('assets/images/play_sequence_8.webp'),

    AssetImage('assets/images/play_sequence_9.webp'),
    AssetImage('assets/images/play_sequence_10.webp'),
    AssetImage('assets/images/play_sequence_11.webp'),

    AssetImage('assets/images/play_sequence_12.webp'),
    AssetImage('assets/images/play_sequence_13.webp'),
    AssetImage('assets/images/play_sequence_14.webp'),

    AssetImage('assets/images/play_sequence_15.webp'),
  ];

  // late AnimationController _IconBtnController;

  @override
  void initState() {
    super.initState();

    _loopPageController = LoopPageController(initialPage: 0);
    _headerLoopPageController = LoopPageController(initialPage: 0,viewportFraction: 0.88);

    robotWhetherOnline = CommonUtil.getCurrentSelectedRobot().isOnline;

    _tween = IntTween(begin: 0, end: signalImages.length - 1);


    eventBus.on<ProductContentEvent>().listen((event) {
      if(event.code == ROBOT_LIST_HAVE_CHANGED) {
        robotWhetherOnline = CommonUtil.getCurrentSelectedRobot().isOnline;
      }
    });


    getActionSquares();

    monitorNetWork();



  }


  void monitorNetWork() async {
    final List<ConnectivityResult> connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult.contains(ConnectivityResult.mobile) || connectivityResult.contains(ConnectivityResult.wifi)) {
      setState(() {
        hasNetWork = true;
      });

    } else {
      setState(() {
        hasNetWork = false;
      });

    }


    mNetSubscription = Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> result) {
      // Received changes in available connectivity types!
      if (result.contains(ConnectivityResult.mobile) || result.contains(ConnectivityResult.wifi)) {
        setState(() {
          hasNetWork = true;
        });
      } else {
        setState(() {
          hasNetWork = false;
        });
      }

    });
  }


  @override
  void dispose() {
    _loopPageController!.dispose();
    /*_signalController.dispose();
    _IconBtnController.dispose();*/

    if (currentIconAnimationController != null) {
      currentIconAnimationController!.dispose();
    }

    if (currentSignalAnimationController != null) {
      currentSignalAnimationController!.dispose();
    }

    if (currentCountDownWatchTimer != null) {
      currentCountDownWatchTimer!.dispose();
    }

    if (mNetSubscription != null) {
      mNetSubscription.cancel();
    }

    //提出动作广场.
    /*ExitSquareActionSkillRequest exitSquareActionSkillRequest = ExitSquareActionSkillRequest();
    MqttCommManager().sendCmd(CmdConst.IM_EXIT_ACTION_SQUARE_REQUEST, exitSquareActionSkillRequest, (AlphaResponse msg) {
    });*/
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          leading: IconButton(
            icon: Image.asset('assets/images/ic_back2.png',width: 48.w,height: 48.h),
            onPressed: () {
              Get.back();
            },
            tooltip: MaterialLocalizations.of(context).backButtonTooltip, // 可选：设置工具提示
          ),
          title: const Text('动作广场'),
          centerTitle: true,
          bottom: !hasNetWork ? PreferredSize(
            preferredSize: Size.fromHeight(72.h),
            child: Container(
              padding: EdgeInsets.only(top: 18.h, bottom: 13.h,left: 40.w),
              color: AppColors.warning_tip_bgColor,
              width: MediaQuery.of(context).size.width,
              child: Text('手机无网络，无法执行动作.',style: TextStyle(fontSize: 26.sp,color: Colors.red)),
            ),
          ) : !robotWhetherOnline ? PreferredSize(
            preferredSize: Size.fromHeight(72.h),
            child: Container(
              padding: EdgeInsets.only(top: 18.h, bottom: 13.h,left: 40.w),
              color: AppColors.warning_tip_bgColor,
              width: MediaQuery.of(context).size.width,
              child: Text('机器人已经离线,无法执行动作.',style: TextStyle(fontSize: 26.sp,color: Colors.red)),
            ),
          ) : PreferredSize(preferredSize: Size.fromHeight(0.h),child: SizedBox())
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(
                flex: 1,
                child: showHeader ? LoopPageView.builder(
                  controller: _headerLoopPageController,
                  itemCount: headerDataSource.length,

                  itemBuilder: (context, index) {
                    ActionItem headerAction = headerDataSource[index];
                    return Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Stack(
                            children: [
                              CachedNetworkImage(
                                imageUrl: headerAction.actionPicture!,
                                errorWidget: (context, url, error) => Image.asset('assets/images/ic_dance_list_default.webp'),
                              ),
                              Container(
                                margin: EdgeInsets.only(left: 50.w,top: 250.h),
                                child: Text(headerAction.actionStatement!,style: TextStyle(fontSize: 32.sp,color: Colors.white)),
                              ),
                              headerAction.isPlaying ? Container(
                                width: 53.w,
                                height: 34.h,
                                margin: EdgeInsets.only(top: 380.h,left: 500.w),
                                child: AnimatedBuilder(
                                  animation: headerAction.signalController!,
                                  child: Image.asset(signalImages[0].toString()), // 初始图片（这里应该是占位图片或第一张图片）
                                  builder: (context, child) {
                                    final index = _tween.evaluate(headerAction.signalController!);
                                    return Stack(
                                      alignment: Alignment.center,
                                      children: List.generate(signalImages.length, (i) =>
                                          Opacity(
                                            opacity: i == index ? 1.0 : 0.0, // 只显示当前索引的图片
                                            child: Image(image: signalImages[i]),
                                          ),
                                      ),
                                    );
                                  },
                                ),
                              ) : SizedBox()
                            ],
                          )
                        ],
                      ),
                    );
                  },
                ) : Image.asset('assets/images/ic_dance_default.webp',width: 540.w,height: 460.h)

            ),
            showHeader ? SizedBox(): Text('点击下方按钮,就能让悟空动起来！',style: TextStyle(fontSize: 30.sp,color: AppColors.Sub_Title_Color)),
            SizedBox(height: 94.h),
            Expanded(flex:2,
              child: Container(
                  color: Colors.white,
                  padding: EdgeInsets.only(top: 60.h),
                  child: Column(
                      children: [
                        Container(child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Stack(
                            children: [
                              danceChecked ? Container(
                                margin: EdgeInsets.only(top: 32.h),
                                child:
                                CommonWidgets.getALine(width: 75,height: 12),) : SizedBox(),
                              GestureDetector(
                                onTap: () {
                                   if (danceChecked) {
                                     return;
                                   }
                                   _loopPageController!.jumpToPage(danceFirsPageIndex);
                                   setState(() {
                                     danceChecked = true;
                                     actionChecked = false;
                                     unexpectedChecked = false;

                                   });
                                },
                                child: Text('舞蹈',style: TextStyle(fontSize: 34.sp,color: AppColors.Sub_Title_Color),
                              )
                              )
                            ],
                          ),
                          SizedBox(width: 62.w,),
                          Stack(
                            children: [
                              actionChecked ? Container(
                                margin: EdgeInsets.only(top: 32.h),
                                child:
                                CommonWidgets.getALine(width: 75,height: 12),) : SizedBox(),
                              GestureDetector(
                                onTap: () {
                                  if (actionChecked) {
                                    return;
                                  }
                                  _loopPageController!.jumpToPage(actionFirsPageIndex);
                                  setState(() {
                                    danceChecked = false;
                                    actionChecked = true;
                                    unexpectedChecked = false;

                                  });
                                },
                                child: Text('动作',style: TextStyle(fontSize: 34.sp,color: AppColors.Sub_Title_Color)),
                              )
                            ],
                          ),
                          SizedBox(width: 62.w,),
                          Stack(
                            children: [
                              unexpectedChecked ? Container(
                                margin: EdgeInsets.only(top: 32.h),
                                child:
                                CommonWidgets.getALine(width: 75,height: 12),): SizedBox(),
                              GestureDetector(
                                onTap: () {
                                  if (unexpectedChecked) {
                                    return;
                                  }
                                  _loopPageController!.jumpToPage(unexpectedFirsPageIndex);
                                  setState(() {
                                    danceChecked = false;
                                    actionChecked = false;
                                    unexpectedChecked = true;

                                  });
                                },
                                child: Text('搞怪',style: TextStyle(fontSize: 34.sp,color: AppColors.Sub_Title_Color)),
                              )
                            ],
                          ),
                        ],
                        )),
                        SizedBox(height: 56.h),
                        Expanded(
                            flex: 1,
                            child: Container(
                              child: ScrollConfiguration(
                                behavior: ScrollConfiguration.of(context).copyWith(
                                  dragDevices: {PointerDeviceKind.touch, PointerDeviceKind.mouse},
                                ),
                                child: LoopPageView.builder(
                                  controller: _loopPageController,
                                  itemCount: groupItems.length,
                                  itemBuilder: (context, index) {
                                    return groupItems[index];
                                  },
                                ),
                              ),
                            )
                        ),
                        dotGroupSize > 0 ?  Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 24),
                          child: PageViewDotIndicator(
                            currentItem: currentIndex,
                            count: dotGroupSize,
                            unselectedColor: Colors.black26,
                            selectedColor: Colors.blue,
                            duration: const Duration(milliseconds: 200),
                            boxShape: BoxShape.circle,
                            size: Size(9.w, 9.h),

                          ),
                        ): SizedBox(),
                        SizedBox(height: 59.h,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset('assets/images/_ic_warm_black.webp',width: 30.w,height: 30.h,),
                            SizedBox(width: 12.w,),
                            Text('注意让悟空保持在安全平整的地方运动,以免磕碰或跌落！',style: TextStyle(fontSize: 24.sp,color: AppColors.Sub_Title_Color)),
                          ],
                        ),
                        SizedBox(height: 47.h,)
                      ],
                    )
              ),)
          ],
        ),
      ),
    );
  }


  void getActionSquares() {
    actionMp.clear();
    //分为在线或不在线.
    if (!robotWhetherOnline) {
      loadingData('Alpha_Mini-UBT','');
    } else {
      GetRobotConfigurationRequest request = GetRobotConfigurationRequest();
      MqttCommManager().sendCmd(CmdConst.IM_GET_ROBOT_CONFIG_REQUEST, request, (AlphaResponse msg){
        GetRobotConfigurationResponse response = GetRobotConfigurationResponse.fromBuffer(msg.bodyData);
        loadingData('Alpha_Mini-UBT',response.hardwareversion);

      });
    }

  }


  void loadingData(String channel,String version) {
    NetWorkManager.getInstance().requestBussiness(NetWorkManager.ACTIONSQUARE_ALL, {
      'channel': channel,
      'version': version,
    }, NetWorkManager.methodGET, DataCallBack(
        businessCallBack: (data) {
          data.forEach((item) {
            ActionItem actionItem = ActionItem.fromJson(item);
            actionItem.iconBtnController =  AnimationController(
              duration: const Duration(seconds: 2),
              vsync: this,
            );

            actionItem.signalController = AnimationController(
              duration: Duration(seconds: 14), // 总动画时长
              vsync: this,
            );

            // 添加定时器.
            actionItem.countDownWatchTimer = StopWatchTimer(
              mode: StopWatchMode.countDown,
              presetMillisecond: actionItem.actionDuration!,
              onEnded: () {

                if (currentIconAnimationController != null && currentIconAnimationController!.isAnimating) {

                  currentIconAnimationController!.reset();
                }


                if (currentSignalAnimationController != null && currentIconAnimationController!.isAnimating)
                currentSignalAnimationController!.reset();

                if (currentActionItem != null)
                currentActionItem!.isPlaying = false;

                actionItem.isPlaying = false;

                if (currentCountDownWatchTimer != null)
                currentCountDownWatchTimer!.onResetTimer();

                generateGridView(actionMp);

              }
            );


            headerDataSource.add(actionItem);
            List<ActionItem> actionItems = actionMp[actionItem.actionType] ?? [];
            actionItems.add(actionItem);
            actionMp[actionItem.actionType!] = actionItems;
          });

          print('actionMp:: ${actionMp}');
          generateGridView(actionMp);

        }
    ));
  }


  void generateGridView(Map<String,List<ActionItem>> actionMp) {
    List<ActionItem> danceActions = actionMp['舞蹈']?? [];
    List<ActionItem> behaviorActions = actionMp['动作']?? [];
    List<ActionItem> unexpectedActions = actionMp['搞怪']?? [];

    List<Widget> danceActionsPages = generatePageViewItem(danceActions);
    List<Widget> behaviorActionsPages = generatePageViewItem(behaviorActions);
    List<Widget> unexpectedActionsPages = generatePageViewItem(unexpectedActions);

    setState(() {
      groupItems.clear();
      danceActionsPages.forEach((item) {
        groupItems.add(item);

      });

      behaviorActionsPages.forEach((item) {
        groupItems.add(item);

      });

      unexpectedActionsPages.forEach((item) {
        groupItems.add(item);

      });

      actionFirsPageIndex = danceActionsPages.length;
      unexpectedFirsPageIndex = danceActionsPages.length + behaviorActionsPages.length;

      dotGroupSize = danceActionsPages.length;

      _loopPageController!.addListener(() {
        // 当页面滚动时更新currentIndex
        var pageNo = _loopPageController!.page ?? 0;
        setState(() {
          int indexPage = pageNo.floor();
          if (indexPage >= 0 && indexPage <= danceActionsPages.length -1) {
             //在跳舞的范围内.
             danceChecked = true;
             actionChecked = false;
             unexpectedChecked = false;

             dotGroupSize = danceActionsPages.length;
             currentIndex = indexPage % dotGroupSize;
          } else if (indexPage > danceActionsPages.length -1 && indexPage <= (danceActionsPages.length + behaviorActionsPages.length-1)) {
            danceChecked = false;
            actionChecked = true;
            unexpectedChecked = false;

            dotGroupSize = behaviorActionsPages.length;
            currentIndex = indexPage % dotGroupSize;
          } else {
            danceChecked = false;
            actionChecked = false;
            unexpectedChecked = true;

            dotGroupSize = unexpectedActionsPages.length;
            currentIndex = indexPage % dotGroupSize;
          }

        });
      });


    });

  }


  // 8 个 icon一页.
  List<Widget> generatePageViewItem(List<ActionItem> datas) {

    List<Widget> pages = [];

    List<ActionItem> onePage = [];
    for (int i = 0; i < datas.length; i++) {
      onePage.add(datas[i]);

      if (onePage.length == 8) {
        pages.add(generateOnePage(onePage));
        onePage.clear();
      } else {
        if (i == datas.length -1) {
          pages.add(generateOnePage(onePage));
          onePage.clear();
        }

      }
    }
    return pages;
  }

  Widget generateOnePage(List<ActionItem> onePage) {

    List<Widget> firstLine = [];
    List<Widget> secondLine = [];
    for (int i = 0; i < onePage.length; i++) {
         ActionItem actionItem =  onePage[i];
         if (firstLine.length < 4) {
           firstLine.add(
               renderOneItem(actionItem,i)
           );
         } else {
           secondLine.add(
               renderOneItem(actionItem,i)
           );
         }

    }

    // 纯属于为了排版整齐.
    int pendingItem1 = 4 - firstLine.length;
    int pendingItem2 = 4 - secondLine.length;

    for (int i = 0; i < pendingItem1; i++) {
      firstLine.add(SizedBox(width: 120.w,));
    }

    for (int j = 0; j < pendingItem2; j++) {
      secondLine.add(SizedBox(width: 120.w,));
    }


    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: firstLine,
        ),
        SizedBox(height: 40.h,),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: secondLine,
        ),
      ],
    );
  }

  Widget renderOneItem (ActionItem actionItem,int index) {
   return  GestureDetector(
      onTap: () async {
       /* if (currentActionItem != null && actionItem.id == currentActionItem!.id && actionItem.isPlaying) {
            return;
        }*/

        if(!(await NetWorkUtil.checkNetWorkIsAvailable())) {
          CommonWidgets.showSingleBtnDialog(Get.context!, "", "手机无网络，请检查网络设置",
              btnText: "知道了", WkEventListener(onClick: (v) {
              }));
          return;
        }


        if(!CommonUtil.getCurrentSelectedRobot().isOnline) {
          CommonWidgets.showSingleBtnDialog(Get.context!, "", "机器人不在线，无法执行动作",
              btnText: "知道了", WkEventListener(onClick: (v) {
              }));
          return;
        }

        if(((CommonUtil.getCurrentSelectedRobot().powerValue??0) < 20) && (CommonUtil.getCurrentSelectedRobot().powerValue??0) > 0) {
          CommonWidgets.showSingleBtnDialog(Get.context!, "", "机器人电量低，无法执行动作",
              btnText: "知道了", WkEventListener(onClick: (v) {
              }));
          return;
        }

        //需要判断是否在播放. 正在播放的是否是复杂动作.
        if (currentActionItem != null &&
            currentActionItem!.isPlaying && currentActionItem!.actionClass =='2' && actionItem.id != currentActionItem!.id) {
          CommonWidgets.showSingleBtnDialog(Get.context!, "", "机器人正在执行复杂动作，请等做完后再试试吧",
              btnText: "知道了", WkEventListener(onClick: (v) {
              }));
          return;
        }

        setState(() {
          showHeader = true;
          if (currentActionItem != null &&
                         actionItem.id == currentActionItem!.id) {

            currentActionItem!.isPlaying = !currentActionItem!.isPlaying;
            //为了刷新isPlaying UI状态.
            generateGridView(actionMp);

            if (currentActionItem!.isPlaying) {
              currentIconAnimationController!.repeat();
              currentSignalAnimationController!.repeat();
              execActionCommends(actionItem);
              actionItem.countDownWatchTimer!.onStartTimer();
            } else {
              if(currentIconAnimationController!.isAnimating)
              currentIconAnimationController!.reset();
              if(currentSignalAnimationController!.isAnimating)
              currentSignalAnimationController!.reset();

              stopActionCommends(actionItem);
              actionItem.countDownWatchTimer!.onResetTimer();
            }


          } else {
            if (currentActionItem != null) {
              currentActionItem!.isPlaying = false;
            }
            actionItem.isPlaying = true;
            currentActionItem = actionItem;

            //为了刷新isPlaying UI状态.
            generateGridView(actionMp);

            if (currentIconAnimationController != null && currentIconAnimationController!.isAnimating) {
              currentIconAnimationController!.reset();
            }
            if (currentSignalAnimationController != null && currentIconAnimationController!.isAnimating) {
              currentSignalAnimationController!.reset();
            }

            actionItem.iconBtnController!.repeat();
            actionItem.signalController!.repeat();

            currentIconAnimationController = actionItem.iconBtnController;
            currentSignalAnimationController = actionItem.signalController;

            Future.delayed(Duration(milliseconds: 500),() {
              for (int i = 0; i < headerDataSource.length; i++) {
                if (headerDataSource[i].id == actionItem.id) {
                  if (_headerLoopPageController!.hasClients) {
                    _headerLoopPageController!.animateToPage(i,duration: Duration(milliseconds: 500), curve: Curves.easeIn);
                  }

                  break;
                }
              }
            });




            actionItem.countDownWatchTimer!.onStartTimer();

            currentCountDownWatchTimer = actionItem.countDownWatchTimer;

            execActionCommends(actionItem);


          }

          //机器人发送过来的消息推送
          MqttCommManager().subScribeEvent(CmdConst.IM_ACTION_SQUARE_INTERUPTER_REQUEST, CustomEventHandler(DataCallBack(
            deviceCallBack: (map) {
              if(currentIconAnimationController!.isAnimating)
                currentIconAnimationController!.reset();
              if(currentSignalAnimationController!.isAnimating)
                currentSignalAnimationController!.reset();

              currentActionItem!.countDownWatchTimer!.onResetTimer();

              currentActionItem!.isPlaying = false;

              generateGridView(actionMp);

            }
          )));

        });
      },
      child:  Container(
        child: Column(
          children: [
            Stack(
              children: [
                AnimatedBuilder(
                  animation: actionItem.iconBtnController!,
                  child: CachedNetworkImage(
                    imageUrl: actionItem.actionIcon!,
                    placeholder: (context, url) => CircularProgressIndicator(),
                    errorWidget: (context, url, error) => Image.asset('assets/images/ic_dance_list_default.webp',width: 120.w,height: 120.h),
                    width: 120.w,
                    height: 120.h,
                  ),
                  builder: (context, child) {
                    // 根据动画值计算旋转角度
                    final double angle = actionItem.iconBtnController!.value * 2.0 * pi;
                    return Transform.rotate(
                      angle: angle, // 应用旋转角度
                      child: child,
                    );
                  },
                ),
                actionItem.isPlaying ? Container(
                  width: 120.w,
                  height: 120.h,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(60.w)),
                    color: Colors.black.withOpacity(0.5),
                  ),

                  child: Container(
                    margin: EdgeInsets.symmetric(horizontal: 35.w,vertical: 35.h),
                    child: Image.asset('assets/images/ic_action_pause.webp',width: 50.w,
                      height: 50.h,),
                  ),
                ) : SizedBox()
              ],
            ),
            SizedBox(height: 11.h,),
            Text(actionItem.actionName!,style: TextStyle(fontSize: 26.sp,color: AppColors.Sub_Title_Color),)
          ],
        ),
      ),
    );
  }

  /**
   * 执行动作广场.
   */
  void execActionCommends (ActionItem actionItem) {
    DoSquareActionRequest doSquareActionRequest = DoSquareActionRequest();
    doSquareActionRequest.resourceName = actionItem.resourceName!;
    doSquareActionRequest.resourceType = actionItem.resourceType!;

    doSquareActionRequest.unsafeAction = actionItem.actionClass == AppConst.HIGH_RISK_ACTION ? true : false;

    if (actionItem.actionUrl != null)
       doSquareActionRequest.resourceUrl = actionItem.actionUrl!;
    if(actionItem.md5 != null)
       doSquareActionRequest.md5 = actionItem.md5!;


    MqttCommManager().sendCmd(CmdConst.IM_ACTION_SQUARE_REQUEST, doSquareActionRequest, (AlphaResponse msg) {
      SquareActionResponse squareActionResponse  = SquareActionResponse.fromBuffer(msg.bodyData);
      if(!squareActionResponse.success && squareActionResponse.errMsg != null) {
           Tips.showToast(squareActionResponse.errMsg);
      }

    });
  }


  void stopActionCommends (ActionItem actionItem) {
    StopSquareActionRequest stopSquareActionRequest = StopSquareActionRequest();
    MqttCommManager().sendCmd(CmdConst.IM_ACTION_STOP_SQUARE_REQUEST, stopSquareActionRequest, (AlphaResponse msg) {
      SquareActionResponse squareActionResponse  = SquareActionResponse.fromBuffer(msg.bodyData);
      if(!squareActionResponse.success && squareActionResponse.errMsg != null) {
        // Tips.showToast(squareActionResponse.errMsg);
        CommonWidgets.showSingleBtnDialog(Get.context!, "", "该动作资源损坏，请先尝试其他动作吧",
            btnText: "知道了", WkEventListener(onClick: (v) {
            }));
      }

    });
  }



}

class CustomEventHandler implements EventHandler  {
  DataCallBack? dataCallBack;

  CustomEventHandler(this.dataCallBack);

  @override
  void handleEvent(AlphaResponse msg) {
    logger.info('动作广场打断事件:: ${msg}');
    if(msg.header.commandId == CmdConst.IM_ACTION_SQUARE_INTERUPTER_REQUEST) {
       dataCallBack!.deviceCallBack!({});

    }
  }

}


